import { api } from './apiClient'
import type { Album, Photo } from '@/types/albums'

export const albumsApi = {
  listAlbums: async (): Promise<Album[]> => {
    const res = await api.get<{ success: boolean; data: Album[] }>('/albums')
    return res.data.data
  },
  createAlbum: async (title: string, coverUrl?: string): Promise<Album> => {
    const res = await api.post<{ success: boolean; data: Album }>('/albums', { title, coverUrl })
    return res.data.data
  },
  updateAlbum: async (id: string, data: Partial<Pick<Album, 'title' | 'coverUrl'>>): Promise<Album> => {
    const res = await api.patch<{ success: boolean; data: Album }>(`/albums/${id}`, data)
    return res.data.data
  },
  deleteAlbum: async (id: string): Promise<void> => {
    await api.delete(`/albums/${id}`)
  },

  listPhotos: async (albumId: string): Promise<Photo[]> => {
    const res = await api.get<{ success: boolean; data: Photo[] }>(`/albums/${albumId}/photos`)
    return res.data.data
  },
  uploadPhoto: async (albumId: string, file: File, meta?: { title?: string; description?: string; tags?: string[]; width?: number; height?: number }): Promise<Photo> => {
    const form = new FormData()
    form.append('file', file)
    if (meta?.title) form.append('title', meta.title)
    if (meta?.description) form.append('description', meta.description)
    if (meta?.width) form.append('width', String(meta.width))
    if (meta?.height) form.append('height', String(meta.height))
    if (meta?.tags?.length) form.append('tags', meta.tags.join(','))
    const res = await api.post<{ success: boolean; data: Photo }>(`/albums/${albumId}/photos`, form, {
      headers: { 'Content-Type': 'multipart/form-data' },
    })
    return res.data.data
  },
  deletePhoto: async (id: string): Promise<void> => {
    await api.delete(`/albums/photos/${id}`)
  },
  toggleLike: async (id: string): Promise<Photo> => {
    const res = await api.post<{ success: boolean; data: Photo }>(`/albums/photos/${id}/like`)
    return res.data.data
  }
}